/**
 * 模态框组件加载器
 * 动态加载库存管理和价格管理模态框组件
 */

// 确定基础路径
function getBasePath() {
    const currentPath = window.location.pathname;
    if (currentPath.includes('/pages/')) {
        return '../components/';
    } else if (currentPath.includes('/modules/product/')) {
        return 'components/';
    } else {
        return '../components/';
    }
}

// 加载库存管理模态框
async function loadInventoryModal() {
    try {
        const basePath = getBasePath();
        const response = await fetch(`${basePath}inventory-modal.html`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const html = await response.text();
        const container = document.getElementById('inventory-modal-container');
        
        if (!container) {
            console.error('Inventory modal container not found');
            return;
        }
        
        container.innerHTML = html;
        console.log('Inventory modal loaded successfully');
        
        // 添加模态框事件监听器
        setupInventoryModalEvents();
        
    } catch (error) {
        console.error('Failed to load inventory modal:', error);
        // 如果加载失败，创建一个错误提示
        createModalLoadErrorMessage('inventory-modal-container', '库存管理模态框');
    }
}

// 加载价格管理模态框
async function loadPricingModal() {
    try {
        const basePath = getBasePath();
        const response = await fetch(`${basePath}pricing-modal.html`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const html = await response.text();
        const container = document.getElementById('pricing-modal-container');
        
        if (!container) {
            console.error('Pricing modal container not found');
            return;
        }
        
        container.innerHTML = html;
        console.log('Pricing modal loaded successfully');
        
        // 添加模态框事件监听器
        setupPricingModalEvents();
        
    } catch (error) {
        console.error('Failed to load pricing modal:', error);
        // 如果加载失败，创建一个错误提示
        createModalLoadErrorMessage('pricing-modal-container', '价格管理模态框');
    }
}

// 设置库存管理模态框事件
function setupInventoryModalEvents() {
    const modal = document.getElementById('inventory-modal');
    if (!modal) return;
    
    // 关闭按钮事件
    const closeBtn = modal.querySelector('.modal-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            if (typeof window.closeInventoryModal === 'function') {
                window.closeInventoryModal();
            }
        });
    }
    
    // 背景点击关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            if (typeof window.closeInventoryModal === 'function') {
                window.closeInventoryModal();
            }
        }
    });
    
    // 标签页切换
    const tabButtons = modal.querySelectorAll('.tab-btn');
    tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const tabName = this.dataset.tab;
            switchInventoryTab(tabName);
        });
    });
}

// 设置价格管理模态框事件
function setupPricingModalEvents() {
    const modal = document.getElementById('pricing-modal');
    if (!modal) return;
    
    // 关闭按钮事件
    const closeBtn = modal.querySelector('.modal-close');
    if (closeBtn) {
        closeBtn.addEventListener('click', function() {
            if (typeof window.closePricingModal === 'function') {
                window.closePricingModal();
            }
        });
    }
    
    // 背景点击关闭
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            if (typeof window.closePricingModal === 'function') {
                window.closePricingModal();
            }
        }
    });
    
    // 标签页切换
    const tabButtons = modal.querySelectorAll('.tab-btn');
    tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const tabName = this.dataset.tab;
            switchPricingTab(tabName);
        });
    });
}

// 库存管理标签页切换
function switchInventoryTab(tabName) {
    const modal = document.getElementById('inventory-modal');
    if (!modal) return;
    
    // 更新标签按钮状态
    const tabButtons = modal.querySelectorAll('.tab-btn');
    tabButtons.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.tab === tabName);
    });
    
    // 更新内容显示
    const tabContents = modal.querySelectorAll('.tab-content');
    tabContents.forEach(content => {
        content.classList.toggle('active', content.id === `${tabName}-tab`);
    });
}

// 价格管理标签页切换
function switchPricingTab(tabName) {
    const modal = document.getElementById('pricing-modal');
    if (!modal) return;
    
    // 更新标签按钮状态
    const tabButtons = modal.querySelectorAll('.tab-btn');
    tabButtons.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.tab === tabName);
    });
    
    // 更新内容显示
    const tabContents = modal.querySelectorAll('.tab-content');
    tabContents.forEach(content => {
        content.classList.toggle('active', content.id === `${tabName}-tab`);
    });
}

// 创建模态框加载错误消息
function createModalLoadErrorMessage(containerId, modalName) {
    const container = document.getElementById(containerId);
    if (!container) return;
    
    container.innerHTML = `
        <div style="
            padding: 20px;
            background-color: #fee;
            border: 1px solid #fcc;
            border-radius: 8px;
            margin: 10px 0;
            text-align: center;
            color: #c33;
        ">
            <i class="fas fa-exclamation-triangle"></i>
            <p>无法加载${modalName}，请检查网络连接或刷新页面重试。</p>
        </div>
    `;
}

// 页面加载完成后加载所有模态框组件
document.addEventListener('DOMContentLoaded', async function() {
    console.log('Starting to load modal components...');
    
    // 只加载库存管理模态框（价格管理模态框已直接嵌入页面）
    try {
        await loadInventoryModal();
        console.log('Inventory modal component loaded');
        
        // 设置ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                const activeModal = document.querySelector('.modal-overlay.active');
                if (activeModal) {
                    if (activeModal.id === 'inventory-modal' && typeof window.closeInventoryModal === 'function') {
                        window.closeInventoryModal();
                    } else if (activeModal.id === 'pricing-modal' && typeof window.closePricingModal === 'function') {
                        window.closePricingModal();
                    }
                }
            }
        });
        
    } catch (error) {
        console.error('Error loading modal components:', error);
    }
});

// 导出函数供其他脚本使用
window.loadInventoryModal = loadInventoryModal;
window.switchInventoryTab = switchInventoryTab;
window.switchPricingTab = switchPricingTab;